<template>
  <div class="w-custom-markdown-parsing" v-html="markedown"/>
</template>

<script lang="ts">
import "@/styles/marked.scss";
import "highlight.js/styles/xcode.css";
import hljs from "highlight.js";
import Marked from "marked";
import { Component, Vue, Prop, Watch } from "vue-property-decorator";

@Component({})
export default class MarkedCustomSprsing extends Vue {
  @Prop({ default: "" }) datastr!: string;

  // 解析的数据
  markedown = "";
  // marked解析对象
  marked = new Marked.Renderer();
  // 定时器（缓存数据转换）
  timer: number = 0;

  @Watch("datastr")
  datastrChange(newVal: string, oldVal: string) {
    this.createTimer(oldVal);
  }

  created() {
    this.initMarked();
  }

  beforeDestroy() {
    this.clearTimer();
  }

  initMarked() {
    const rendererMD = new Marked.Renderer();
    Marked.setOptions({
      renderer: rendererMD,
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: false,
      smartLists: true,
      smartypants: false
    });
    Marked.setOptions({
      highlight: function(code: any) {
        return hljs.highlightAuto(code).value;
      }
    });
  }

  createTimer(oldVal: string) {
    if (this.datastr.length < 300 || !oldVal) {
      this.markedown = Marked(this.datastr);
      this.clearTimer();
      return;
    }
    this.clearTimer();
    this.timer = setTimeout(() => {
      this.markedown = Marked(this.datastr);
    }, 500);
  }

  clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  }
}
</script>

<style lang="scss" scoped>
.w-custom-markdown-parsing {
  padding: 0 5px;
}
</style>
